package com.maiyuren.fishkit.utils

import android.os.Build
import androidx.annotation.RequiresApi
import com.maiyuren.fishkit.FishkitApplication
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.RandomAccessFile


object FishAssetsFileUtils {
    /**
     * 采用这个方法进行打开文件，会将文件复制到SD卡中
     * 因为安卓限制1M文件不能直接读取，所以需要复制出去。
     */
    fun open(path: String): RandomAccessFile? {
        // 先拿当前版本
        val cfgKey = "${FishStorage.keys.assets_file_pre}${path}"
        val lastVer = FishStorage.getString(cfgKey)
        val currAppVersion = FishAppUtils.getVersion()
        if (null == currAppVersion) return null
        val sdFilePath = FishkitApplication.instance.filesDir.absolutePath + "/assets/" + path
        val sdFile = File(sdFilePath)

        // 如果有APP更新，则直接替换，并更新配置为当前版本，避免重复复制
        if (currAppVersion != lastVer || !sdFile.exists()) {
            val folderPathPos = sdFilePath.lastIndexOf('/')
            val folderPath  = sdFilePath.substring(0, folderPathPos)
            File(folderPath).mkdirs()
            val tempStream: InputStream = FishkitApplication.instance.assets.open(path)
            val outStream = FileOutputStream(sdFile, false)
            val tempBuffer = ByteArray(64 * 1024) // 64K per time

            while (tempStream.available() > 0) {
                val readLen = tempStream.read(tempBuffer)
                if (readLen > 0) {
                    outStream.write(tempBuffer, 0, readLen)
                }
                if (readLen < 64 * 1024) {
                    break
                }
            }

            outStream.close()

            tempStream.close()
            FishStorage.setString(cfgKey, currAppVersion)
        }

        return RandomAccessFile(sdFile, "r");
    }

    fun readAllContentOfStringFile(path: String): String? {
        val stream = FishkitApplication.instance.assets.open(path)
        val buf = stream.readBytes()
        stream.close()
        return buf?.toString(Charsets.UTF_8);
    }

    fun readJsonObjectFile(path: String): JSONObject? {
        val content = this.readAllContentOfStringFile(path)
        if (content == null) return null
        return JSONObject(content);
    }

    fun readJsonArrayFile(path: String): JSONArray? {
        val content = this.readAllContentOfStringFile(path)
        if (content == null) return null
        return JSONArray(content);
    }
}